package com.tianji.learning.utils;

import lombok.Data;

import java.time.Duration;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

@Data
public class DelayQueueTask<D> implements Delayed {
    private Long taskTime;
    private D data;

    public DelayQueueTask(Duration duration, D data) {
        this.taskTime = System.nanoTime() + duration.toNanos();
        this.data = data;
    }
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(Math.max(taskTime - System.nanoTime(), 0),TimeUnit.NANOSECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        Long a = this.getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS);
        if (a > 0) {
            return 1;
        } else if (a < 0) {
            return -1;
        } else {
            return 0;
        }
    }
}
